import { Model } from "sequelize";
import SecretKeyChunkModel from "../models/SecretKeyChunkModel";
import { keyChunkStatus } from "../models/enums";

interface IPutOption {
  id?: string
  beginTime?: string
  status?: keyChunkStatus
  result?: string
  reserve?: string
}

export interface IFindByPageOption {
  /**
   * 状态
   */
  status?: keyChunkStatus
  /**
   * 结果
   */
  result?: string
}

export default class KeyChunkDao {

  /**
   * 创建 密钥块
   * @param BeginPos 
   * @deprecated 密钥块 初始化好，分为 2^17（131072） 块，每块 2^16(65536) 个
   * @param EndPos 
   * @returns 
   */
  static async create(beginPos: number, endPos: number) {

    const result = await SecretKeyChunkModel.create({
      beginPos,
      endPos
    })
    return result.toJSON()
  }

  /**
   * 获取一个未分配的 密钥块
   * @returns 
   */
  static async getOneUndistributed() {
    let result = await SecretKeyChunkModel.findOne({
      where: {
        status: keyChunkStatus.undistributed
      }
    })

    if (result) {
      result = result.toJSON()
    } else {
      // 没有找到时
      result = ({} as Model<any, any>)
    }

    return result
  }

  static async getRight() {
    const { rows, count } = await SecretKeyChunkModel.findAndCountAll({
      where: {
        status: keyChunkStatus.over,
      },
      attributes: ['right']
    })

    return {
      data: rows,
      total: count
    }

  }

  /**
   * 修改一个密钥块
   * @param option 
   * @returns 
   */
  static async putOneKey(option: IPutOption) {
    const values = {
      ...option
    }

    delete values.id

    const result = await SecretKeyChunkModel.update({
      ...values
    }, {
      where: {
        id: option.id
      }
    })

    if (result[0] > 0) {
      return true
    } else {
      return false;
    }
  }

  /**
   * 分页查找
   * @param offset 偏移量
   * @param limit 页容量
   * @param options 查找条件
   * @returns 
   */
  static async findByPage(offset: number = 0, limit = 10, options: IFindByPageOption = {}) {
    const { rows, count } = await SecretKeyChunkModel.findAndCountAll({
      where: {
        ...options
      },
      limit,
      offset
    })

    return {
      data: rows,
      total: count
    }

  }

  static async statusStatistics() {
    const undistributed = await SecretKeyChunkModel.count({
      where: {
        status: keyChunkStatus.undistributed
      }
    })

    const awaitResult = await SecretKeyChunkModel.count({
      where: {
        status: keyChunkStatus.await
      }
    })

    const over = await SecretKeyChunkModel.count({
      where: {
        status: keyChunkStatus.over
      }
    })

    return [
      {
        value: undistributed,
        name: '未分配'
      },
      {
        value: awaitResult,
        name: '等待结果'
      },
      {
        value: over,
        name: '计算完成'
      },
    ]

  }

}